import numpy as np
import time
from tqdm import trange
from CION_Sequencer import *

# -------- PWM Test --------

def PWM_Test():
    max_t = 100000
    step = 300
    x = np.linspace(0, np.pi, step)
    y = (0.5 - 0.498 * np.cos(x)) * max_t
    f = CfgFlow(C_CION_SEQR)
    with f:
        for i in range(step):
            DatCacheWrite(i, round(y[i]))
    Run(f)

    pwm_test = NewExperiment()
    with pwm_test:
        with AutoBubble(0):
            with Subroutine("flash"):
                with Repeat(R.R4, 5):
                    TTL_Stage(2, R.R2, R.DCD)
                    TTL_Stage(2, R.R3, max_t - R.DCD)
            # Main
            StartTimedTask(130)
            R.R2 = 0x11111111
            with LoopForever():
                R.R3 = R.R2
                R.R2 = SLC(R.R2, 1)
                with Scan(R.R1, 0, step, 1):
                    R.DCA = R.R1
                    Call("flash")
    Run(pwm_test)

# -------- Counter & TTL Test --------

def CntrTTL(ttl_chn, cntr, rep):
    """
    
    TTL - counter loopback test.
    Connect TTL output ports to the counter input ports to perform the test.

    Parameters
    ----------
    ttl_chn : int
        TTL output channel.
    cntr : list
        List of counter channels.
    rep : int
        Number of TTL pulses to be generated.

    Prints
    -------
    Counts of the designated counter channels.

    """
    f = NewExperiment()
    with f:
        TTL_Stage(ttl_chn, 0, 0.1)
        Cntr_ON(cntr)
        with Repeat(R.R0, rep):
            TTL_Stage(ttl_chn, 0xFFFFFFFF, 0.1)
            TTL_Stage(ttl_chn, 0, 0.1)
        Cntr_OFF(cntr)
        GetCounts(cntr)
    res = Run(f, len(cntr))
    print(res)

# -------- External Trigger Test --------

def TrigTest():
    """
    
    TTL - external trigger loopback test.
    The LEDs should blink if the external trigger input port is
    connected to any TTL output port.

    Returns
    -------
    None.

    """
    f = NewExperiment()
    with f:
        TTL_Stage(0, 0xFFFFFFFF, 0.1)
        TTL_Stage(1, 0xFFFFFFFF, 0.1)
        TTL_Stage(2, 0xF, 0.1)
        with LoopForever():
            ExtTrigger()
            TTL_Stage(2, 0xF, 100000.0)
            TTL_Stage(2, 0x0, 100000.0)
    Run(f)
